package com.xunfang.CameraImage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

/*
 * 这个类是用来实现手机相机的类
 */
public class CameraImageActivity extends Activity {
	/** Called when the activity is first created. */
	//
	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHoler;
	private int screenWidth, screenHeight;
	private ImageButton imagebutton, imageb;
	// 定义系统摄像头
	private Camera camera;
	private boolean isPreview = false;
	private File previewFile;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 固定屏幕方向
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		// 设置全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);

		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();

		// 获取屏幕尺寸
		screenWidth = display.getWidth();
		screenHeight = display.getHeight();
		System.out.println(screenWidth + "-------" + screenHeight);
		// 根据组件ID获取组件
		imagebutton = (ImageButton) findViewById(R.id.imagebutton);
		imagebutton.setBackgroundColor(Color.BLACK);
		imageb = (ImageButton) findViewById(R.id.imageb);
		imageb.setBackgroundColor(Color.BLACK);

	}

	protected void onStart() {
		// TODO Auto-generated method stub
		// 判断SD卡是否存在
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "请先插入SD卡！", 5000).show();
			imagebutton.setEnabled(false);
		}
		// 设置按钮监听事件
		imagebutton.setOnClickListener(new ImageButtonOnClick());
		imageb.setOnClickListener(new ImageButtonOnClick());
		surfaceView = (SurfaceView) findViewById(R.id.sv);
		// 获取SurfaceHoler
		surfaceHoler = surfaceView.getHolder();

		surfaceHoler.addCallback(new Callback() {
			// 当surface创建时初试化摄像头

			public void surfaceCreated(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				initCamera();// 初始化摄像头
			}

			public void surfaceChanged(SurfaceHolder holder, int format,
					int width, int height) {
				// TODO Auto-generated method stub

			}

			// 当surface销毁时释放资源

			public void surfaceDestroyed(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				// 如果Camera不为null,释放摄像头
				if (camera != null) {
					if (isPreview) {
						camera.stopPreview();// 停止预览
						camera.release();// 释放资源
						isPreview = false;
						camera = null;
					}
				}
			}

		});
		// 设置SurfaceView自己不维护缓存
		surfaceHoler.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		super.onStart();
	}

	/*
	 * 初始化摄像头并设置参数
	 */
	private void initCamera() {
		System.out.println("isPreview is---" + isPreview);
		if (!isPreview) {
			try {
				camera = Camera.open();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}// 打开摄像头
		}
		if (camera != null && !isPreview) {
			try {
				Camera.Parameters parameters = camera.getParameters();
				// 设置预览照片的大小
				// parameters.setPreviewSize(screenWidth, screenHeight);
				parameters.setPreviewSize(640, 480);
				// 每秒显示4帧
				parameters.setPreviewFrameRate(4);
				// 设置图片格式
				parameters.setPictureFormat(PixelFormat.JPEG);
				// 设置JPG照片的质量
				parameters.set("jpeg-quality", 85);
				// 设置照片的大小
				// parameters.setPictureSize(screenWidth, screenHeight);
				// parameters.setPictureSize(2048, 1536);
				parameters.setPictureSize(640, 480);
				camera.setParameters(parameters);
				// 通过SurfaceView显示取景画面
				camera.setPreviewDisplay(surfaceHoler);
				// 开始预览
				camera.startPreview();
				// 自动对焦
				camera.autoFocus(null);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			isPreview = true;
		}
	}

	/*
	 * 内部类，用于实现OnClickListener接口
	 */
	class ImageButtonOnClick implements OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.imagebutton:
				if (camera != null) {
					imagebutton.setVisibility(View.INVISIBLE);
					// 启动绘制图片
					camera.takePicture(null, null, myjpegCallback);
				}
				break;
			case R.id.imageb:
				System.out.println(previewFile.getPath());
				// 设置在系统中选择打开文件的方式
				Intent intent = new Intent();
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setAction(android.content.Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(previewFile), "image/*");
				startActivity(intent);
				break;
			default:
				break;
			}

		}
	}

	PictureCallback myjpegCallback = new PictureCallback() {

		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			// 根据拍照所得的数据创建位图
			previewFile = null;
			final Bitmap bm = BitmapFactory.decodeByteArray(data, 0,
					data.length);

			// 显示拍摄的照片
			Bitmap bm1 = Bitmap.createScaledBitmap(bm, imageb.getWidth(),
					imageb.getHeight(), false);
			imageb.setImageBitmap(bm1);
			// 实例化时间
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("HHmmssSSS");// 格式化时间
			String pictureName = "IMG_" + sdf.format(date) + "_"
					+ sdf1.format(date);
			// 创建保持图像目录
			File folder = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "DCIM" + File.separator + "Camera");
			// 判断文件目录是否存在
			if (!folder.exists()) {
				folder.mkdir();
			}
			// 创建图像文件
			File file = new File(folder.getPath() + File.separator, pictureName
					+ ".jpg");
			System.out.println("文件保存路径：" + file.getPath());
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(file);// 实例话文件输出流
				bm.compress(CompressFormat.JPEG, 100, out);// 绘制图像并按JPEG格式保存
				try {
					out.flush();// 刷新缓存区
					out.close();// 关闭输出流
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					previewFile = file;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 重新浏览
			imagebutton.setVisibility(View.VISIBLE);
			camera.stopPreview();
			camera.startPreview();
			isPreview = true;

		}
	};

}